package com.jianyun.jyzs.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.SelectPersonAdpater;
import com.jianyun.jyzs.base.MVPBaseActivity;
import com.jianyun.jyzs.bean.SelectedContactInfo;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.constant.PinConstant;
import com.jianyun.jyzs.dao.UserDao;
import com.jianyun.jyzs.presenter.SelectPresenPresenter;
import com.jianyun.jyzs.utils.Const;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.ISelectContactView;
import com.jianyun.jyzs.widget.CrumbView;
import com.jianyun.jyzs.widget.SelectConfig;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jianyun.jyzs.utils.RceLog;

/**
 * Created by yangshijun on 2018/7/17.
 * 选择联系人界面
 */

public class SelectContact2Activity extends MVPBaseActivity<ISelectContactView, SelectPresenPresenter>
        implements ISelectContactView {
    @BindView(R.id.createGroupCrumb)
    CrumbView departmentCrumbView;
    @BindView(R.id.departmentDivider)
    View departmentDivider;
    @BindView(R.id.selectAllCheckBox)
    ImageView selectAllCheckBox;
    @BindView(R.id.createGroupSelectAll)
    LinearLayout createGroupSelectAll;
    @BindView(R.id.selectedContactsCountTextView)
    TextView selectedContactsTextView;
    @BindView(R.id.confirmButton)
    TextView confirmButton;
    @BindView(R.id.summaryLinearLayout)
    LinearLayout summaryLinearLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private final static String TAG = SelectContactActivity.class.getSimpleName();
    public static final int FROM_CREATE_GROUP = 222;
    public static final int FROM_GROUP_ADD_STAFF = 111;
    public static final int FROM_FORWARD = 000;
    //此处不能做 public
    public static LinkedHashMap<String, SelectedContactInfo> selectedContactInfoList;
    public ArrayList<String> initialList;
    private int maxSelectCount = Integer.MAX_VALUE;
    protected String currentDepartId;
    private SelectConfig selectConfig;
    private ArrayList<String> uncheckableListId;
    private String userId;
    private String enterpriseCode;
    private SelectPersonAdpater adpater;
    private List<User> userList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rce_activity_create_group);
        ButterKnife.bind(this);
        selectConfig = getIntent().getParcelableExtra(Const.SELECT_CONFIG);
        if (selectConfig == null) {
            selectConfig = new SelectConfig();
        }
        init();
    }


    private void init() {
        try {
            selectedContactInfoList = new LinkedHashMap<>();
            maxSelectCount = selectConfig.getMaxSelectedNumber();
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            userId = LoginCache.getInstance().getUserInfo().getUserId();
            enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
            userList = new UserDao(this).queryConstants(enterpriseCode, userId);
            adpater = new SelectPersonAdpater(this, null, userId);
            recyclerView.setAdapter(adpater);
            if (userList != null && userList.size() > 0) {

                adpater.setList(userList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        adpater.setMaxSelectCount(maxSelectCount);
        //setSelectedContactViewProperty();
        adpater.addItemClickListener(new SelectPersonAdpater.ItemClickListener() {
            @Override
            public void onEnterDepartment(Map<String, String> path) {
                departmentCrumbView.setVisibility(View.VISIBLE);
                departmentDivider.setVisibility(View.VISIBLE);
                createGroupSelectAll.setVisibility(View.VISIBLE);

                for (String key : path.keySet()) {
                    if (departmentCrumbView.getPieceCount() == 0) {
                        departmentCrumbView.setRootPiece(path.get(key), key);
                        currentDepartId = null;
                    } else {
                        departmentCrumbView.addPiece(path.get(key), key);
                        currentDepartId = key;
                    }
                }
                boolean clickable = adpater.isClickable();
                createGroupSelectAll.setClickable(clickable);
                if (!adpater.isSelectedAll()) {
                    selectAllCheckBox.setImageResource(R.drawable.rce_ic_checkbox_none);
                } else {
                    selectAllCheckBox.setImageResource(clickable ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_full_gray);
                }
            }

            @Override
            public void onContactChecked(SelectedContactInfo contactInfo, boolean checked) {
                if (checked) {
                    SelectedContactInfo prvContact = selectedContactInfoList.put(contactInfo.getId(), contactInfo);
                    if (prvContact != null) {
                        contactInfo.setCheckable(prvContact.isCheckable());
                    }
                } else {
                    if (contactInfo.isCheckable()) {
                        selectedContactInfoList.remove(contactInfo.getId());
                    }
                }
                setSelectedContactViewProperty();
                //createGroupSelectAll.setClickable(true);
                // selectAllCheckBox.setImageResource(adpater.isSelectedAll() ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_none);
            }
        });
        handleInitialSelect();

    }


    protected void setSelectedContactViewProperty() {
        int count = 0;
        for (SelectedContactInfo info : selectedContactInfoList.values()) {
            if (info.isCheckable()) {
                count++;
            }
        }
        count = count + getExtraSelectedCount();
        selectedContactsTextView.setClickable(count > 0);
        selectedContactsTextView.setTextColor(count > 0 ? getResources().getColor(R.color.color_primary) :
                getResources().getColor(R.color.color_gray_text));
        setSelectedShowText();

        confirmButton.setClickable(count > 0);
        confirmButton.setTextColor(count > 0 ?
                getResources().getColor(R.color.color_primary) :
                getResources().getColor(R.color.color_gray_text));
    }


    private void setSelectedShowText() {
        List<SelectedContactInfo> groupList = new ArrayList<>();
        int count = 0;
        if (selectedContactInfoList != null) {
            for (SelectedContactInfo selectedContactInfo : selectedContactInfoList.values()) {
                if (selectedContactInfo.isCheckable()) {
                    count++;
//                    groupList.add(selectedContactInfo);
//                    if (!(selectedContactInfo.getConversationType() == null)) {
//                        if (selectedContactInfo.getConversationType().equals(Conversation.ConversationType.GROUP)) {
//                            groupList.add(selectedContactInfo);
//                        }
//                    }
                }
            }
            count = count + getExtraSelectedCount();
            int groupCount = groupList.size();
            int privateCount = count - groupCount;
            if (groupCount == 0) {
                selectedContactsTextView.setText(getString(R.string.rce_selected_contacts_count, count));
            } else if (privateCount == 0) {
                selectedContactsTextView.setText(getString(R.string.rce_selected_only_group, groupCount));
            } else {
                selectedContactsTextView.setText(getString(R.string.rce_selected_contacts_count, privateCount) + getString(R.string.rce_selected_groups_count, groupCount));
            }
        }
    }

    private void handleInitialSelect() {
        initialList = selectConfig.getInitialSelectList();
        uncheckableListId = selectConfig.getUnCheckableList();
        if (selectConfig.isSelfCheck()) {
            uncheckableListId.remove(userId);
            initialList.remove(userId);
        }
        if (userList != null && userList.size() > 0) {
            for (User user : userList) {
                SelectedContactInfo contactInfo = new SelectedContactInfo();
                contactInfo.setId(user.getServerUserId());
                contactInfo.setName(user.getNameZh());
                contactInfo.setPortraitUrl(user.getServerIconPath());
                //contactInfo.setDepartPath(user.get());
                contactInfo.setDepartName(user.getDepartment());
                //如果是自己那么置灰，如果还有其他在config中处于uncheckableList的,也置灰
                if (initialList.contains(user.getServerUserId())) {
                    contactInfo.setCheckable(!uncheckableListId.contains(user.getServerUserId()));
                    contactInfo.setPhoneNumber(user.getPhoneNum());
                    selectedContactInfoList.put(contactInfo.getId(), contactInfo);
                }
            }
        }
        adpater.notifyDataSetChanged();
        setSelectedContactViewProperty();


    }

    @Override
    public void onCreateActionBar(ActionBar actionBar) {
        super.onCreateActionBar(actionBar);
        actionBar.setTitle(getString(R.string.rce_select_contact));
        actionBar.setOptionDrawable(getResources().getDrawable(R.drawable.rce_ic_nav_option_search));
        actionBar.setOptionVisible(View.INVISIBLE);
    }

    /**
     * 一般都是从系统内部选人，但是电话会议等的模块可以从手机通讯录选人，
     * 在显示选择人员数目时需要计算手机通讯里选择的人数，提供这个接口，子类可以提供手机通讯录选择的人数
     */
    protected int getExtraSelectedCount() {
        return 0;
    }

    @Override
    protected void onDestroy() {
        RceLog.d(TAG, "onDestroy");
        if (selectedContactInfoList != null) {
            selectedContactInfoList.clear();
            selectedContactInfoList = null;
        }
        super.onDestroy();
    }

    @NonNull
    @Override
    public SelectPresenPresenter createPresenter() {
        return new SelectPresenPresenter();
    }

    public static LinkedHashMap<String, SelectedContactInfo> getSelectedList() {
        return selectedContactInfoList;
    }

    public void exceedMaxSelectCount() {
        if (maxSelectCount == PinConstant.PIN_MAX_SELECT_NUMBER) {
            Toast.makeText(SelectContact2Activity.this, getString(R.string.rce_pin_max_receiver_number, selectConfig.getMaxSelectedNumber() - 1), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, getString(R.string.rce_select_contact_exceed_max_count), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onOptionClick() {
        super.onOptionClick();
        //搜索

    }

    @OnClick(R.id.confirmButton)
    public void onViewClicked() {
        List<String> resultList = new ArrayList<>();
        ArrayList<User> users = new ArrayList<>();
        for (String key : selectedContactInfoList.keySet()) {
            resultList.add(key);
        }
        if (selectedContactInfoList != null && selectedContactInfoList.size() > 0) {
            try {
                for (int i = 0; i < selectedContactInfoList.size(); i++) {
                    SelectedContactInfo selectedContactInfo = selectedContactInfoList.get(resultList.get(i));
                    User user = new User();
                    user.setServerUserId(selectedContactInfo.getId());
                    user.setName(selectedContactInfo.getName());
                    user.setServerIconPath(selectedContactInfo.getPortraitUrl());
                    //contactInfo.setDepartPath(user.get());
                    user.setDepartment(selectedContactInfo.getDepartName());
                    //如果是自己那么置灰，如果还有其他在config中处于uncheckableList的,也置灰
                    //user.setCheckable(!uncheckableListId.contains(user.getServerUserId()));
                    user.setPhoneNum(selectedContactInfo.getPhoneNumber());
                    users.add(user);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.i("test", "users:" + users.toString());
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Const.SELECTED_CONTACTS,(Serializable) users);
        intent.putExtras(bundle);
        //intent.putParcelableArrayListExtra(Const.SELECTED_CONTACTS, users);
        setResult(Activity.RESULT_OK, intent);
        finish();

    }
}
